/**
 * Project Name:dyrj-admin
 * File Name:RoleServiceImpl.java
 * Package Name:com.dyrj.base.system.role.service.impl
 * Date:2018年1月29日下午12:44:48
 * Copyright (c) 2018, zhang.xiangyu@foxmail.com All Rights Reserved.
*/
package com.dyrj.base.system.role.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.dyrj.constant.SysFrameConst;
import com.dyrj.vo.PageResultMsg;
import freemarker.template.utility.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.dyrj.base.system.menu.dao.SysMenuMapper;
import com.dyrj.base.system.menu.model.SysMenu;
import com.dyrj.base.system.role.dao.SysRoleMapper;
import com.dyrj.base.system.role.dao.SysUserRoleLinksMapper;
import com.dyrj.base.system.role.model.SysRole;
import com.dyrj.base.system.role.service.RoleService;
import com.dyrj.base.system.user.model.SysUser;
import com.dyrj.vo.ResultMsg;

/**   
 * @Title: RoleServiceImpl.java 
 * @Package com.dyrj.base.system.role.service.impl
 * @Description: TODO(系统管理-角色) 
 * @author
 * @date 2018年1月29日 下午12:44:48 
 * @version V1.0   
 */
@Service
public class RoleServiceImpl  implements RoleService {
	@Resource
	private SysRoleMapper mapper;
	@Resource
	private SysUserRoleLinksMapper linksMapper;
	@Resource
	private SysMenuMapper menuMapper;
	
	@Override
	public PageResultMsg table(SysRole record) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		record.setLoginUser(sysUser.getAccount());
		PageInfo<SysRole> page = PageHelper.startPage(record.getOffset(), record.getLimit()).doSelectPageInfo(() -> mapper.selectPage(record));
		return new PageResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, page.getTotal(), page.getList());
	}
	
	@Override
	public List<SysRole> findRoles() {
		return mapper.selectPage(null);
	}

	@Override
	public ResultMsg add(SysRole record) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		record.setCreateTime(new Date());
		record.setTenantid(sysUser.getTenantid());
		mapper.insertSelective(record);
		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
	}
	
	@Override
	public SysRole info(Long id) {
		SysRole role = mapper.selectByPrimaryKey(id);
		List<SysMenu> menus = menuMapper.selectAllTreeMenu();
		menus = this.checkedMenus(menus, role.getRoleSign());
		role.setMenus(menus);
		return role;
	}
	@Override
	public SysRole multyInfo(String id ) {
		SysRole role =null;
		String roleSign=null;
		if(id!=null&&id.length()>0) {
			String idArr[] = id.split(",");
			for(int i=0;i<idArr.length;i++) {
				role = mapper.selectByPrimaryKey(Long.valueOf(idArr[i]));
				if(i==0) {
					roleSign =role.getRoleSign();
				}else{
					roleSign=roleSign+","+role.getRoleSign();
				}
			}
		}
		if(role!=null) {
			List<SysMenu> menus = menuMapper.selectAllTreeMenu();
			menus = this.checkedMenus(menus, roleSign);
			role.setMenus(menus);
		}
		return role;
	}
	@Override
	public ResultMsg update(SysRole record) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		record.setTenantid(sysUser.getTenantid());
		record.setUpdateTime(new Date());
		mapper.updateByPrimaryKeySelective(record);
		// 更新角色信息成功后刷新session中权限
		List<SysRole> roles = mapper.selectRoleByUserId(sysUser.getId());
		SecurityUtils.getSubject().getSession().setAttribute(SysFrameConst.SYSTEM_ROLES, roles);
		
		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
	}
	@Override
	public ResultMsg addAuthUpdate(SysRole record) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		record.setTenantid(sysUser.getTenantid());
		record.setUpdateTime(new Date());
		String id = record.getCreateTimeVo();
		String idArr[] = id.split(",");
		for(int i=0;i<idArr.length;i++) {
			SysRole tempRole = mapper.selectByPrimaryKey(Long.valueOf(idArr[i]));
			tempRole.setRoleSign(record.getRoleSign());
			tempRole.setRoleView(record.getRoleView());
			mapper.updateByPrimaryKeySelective(tempRole);
		}
		// 更新角色信息成功后刷新session中权限
		List<SysRole> roles = mapper.selectRoleByUserId(sysUser.getId());
		SecurityUtils.getSubject().getSession().setAttribute(SysFrameConst.SYSTEM_ROLES, roles);

		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
	}
	@Override
	public ResultMsg muliUpdate(SysRole record) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		record.setTenantid(sysUser.getTenantid());
		record.setUpdateTime(new Date());
		String id = record.getCreateTimeVo();
		String idArr[] = id.split(",");
		String sign = record.getRoleSign();
		String signArr[] = StringUtil.split(sign, ':');
		String view = record.getRoleView();
		String viewArr[] = StringUtil.split(view, ':');
//		System.out.println(idArr.length+"==========="+signArr.length+"================="+viewArr.length);
            for (int i = 0; i < idArr.length; i++) {
//                System.out.println(id + "=role=" + idArr[i]);
                SysRole tempRole = mapper.selectByPrimaryKey(Long.valueOf(idArr[i]));
                if("空".equals(signArr[i])&&"空".equals(viewArr[i])) {
                    tempRole.setRoleSign("");
                    tempRole.setRoleView("");
                }else{
                    tempRole.setRoleSign(signArr[i]);
                    tempRole.setRoleView(viewArr[i]);
                }
                mapper.updateByPrimaryKey(tempRole);
            }
		// 更新角色信息成功后刷新session中权限
		List<SysRole> roles = mapper.selectRoleByUserId(sysUser.getId());
		SecurityUtils.getSubject().getSession().setAttribute(SysFrameConst.SYSTEM_ROLES, roles);

		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
	}
	public static void main(String args[]){
	    String view="空:空";
        String viewArr[] =  StringUtil.split(view, ':');
        System.out.println(viewArr[0]+viewArr.length);
    }
	@Override
	public ResultMsg remove(SysRole record) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		record.setTenantid(sysUser.getTenantid());
		record.setUpdateTime(new Date());
		mapper.updateByPrimaryKeySelective(record);
		// 更新角色信息成功后刷新session中权限
		List<SysRole> roles = mapper.selectRoleByUserId(sysUser.getId());
		SecurityUtils.getSubject().getSession().setAttribute(SysFrameConst.SYSTEM_ROLES, roles);

		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
	}

	@Override
	public ResultMsg del(Long id) {
		mapper.deleteByPrimaryKey(id);
		linksMapper.deleteUserRoleLinksByRoleId(id);
		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
	}
	
	/**
	 * @Title: deleteNullChildren 
	 * @Description: TODO(递归清除空children) 
	 * @param menus
	 * @return List<SysMenu>    返回类型
	 */
	private List<SysMenu> checkedMenus(List<SysMenu> menus, String perms) {
		for(SysMenu info : menus) {
			if(perms.contains(info.getPerms())) {
				info.setChecked(true);
			}
			if(info.getChildren().isEmpty()) {
				info.setChildren(null);
			} else {
				this.checkedMenus(info.getChildren(), perms);
			}
		}
		return menus;
	}
}
